package handlers

import (
	"fmt"
	"github.com/dgrijalva/jwt-go"
	"github.com/emicklei/go-restful"
	"kubeInstall/pkg/auth/jwtauth"
	"net/http"
)

type middlewareHandler struct {
	BaseHandler
}

func (m middlewareHandler) ValidateTokenFilter(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) {

	token := req.HeaderParameter("Authorization")
	if token == "" {
		m.RenderError(resp, "Not Authorized", http.StatusUnauthorized)
		return
	}

	_, err := jwtauth.Auth.ParseToken(token)

	if err != nil {
		switch err.(*jwt.ValidationError).Errors {
		case jwt.ValidationErrorExpired:
			m.RenderError(resp, "Token is Expired", http.StatusForbidden)
			return
		case jwt.ValidationErrorMalformed:
			m.RenderError(resp, "Token is invalid", http.StatusForbidden)
			return
		default:
			m.RenderError(resp, fmt.Sprintf("Parse Token failed,error is: %v", err), http.StatusForbidden)
			return
		}
	}

	chain.ProcessFilter(req, resp)

}

func NewMiddlewareHandler() *middlewareHandler {
	return new(middlewareHandler)
}
